/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.inventory.web;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.modules.inventory.entity.*;
import com.thinkgem.jeesite.modules.inventory.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.Collections3;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.duty.entity.ZlmtDutySheet;
import com.thinkgem.jeesite.modules.duty.entity.ZlmtMaintenanceRecord;
import com.thinkgem.jeesite.modules.duty.service.ZlmtDutySheetService;
import com.thinkgem.jeesite.modules.duty.service.ZlmtMaintenanceRecordService;

/**
 * 资产管理Controller
 * @author johnKee
 * @version 2016-07-20
 */
@Controller
@RequestMapping(value = "${adminPath}/inventory/hostInventory")
public class HostInventoryController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(HostInventoryController.class);

	@Autowired
	private HostInventoryService hostInventoryService;

	@Autowired
	private ZlmtCabinetService zlmtCabinetService;

	@Autowired
	private ZlmtHostsCabinetService zlmtHostsCabinetService;

	@Autowired
	private ZlmtHostsAccessoryService zlmtHostsAccessoryService;

	@Autowired
	private ZlmtResourceUserService zlmtResourceUserService;

	@Autowired
	private ZlmtMaintenanceRecordService zlmtMaintenanceRecordService;

	@Autowired
	private HostLinksService hostLinksService;
	
	@Autowired
	private ZlmtDutySheetService zlmtDutySheetService;
	

	@ModelAttribute
	public HostInventory get(@RequestParam(required=false) String id) {
		HostInventory entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = hostInventoryService.get(id);
		}
		if (entity == null){
			entity = new HostInventory();
		}
		return entity;
	}
	
	@RequestMapping(value = {"list", ""})
	public String list(HostInventory hostInventory, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<HostInventory> page = hostInventoryService.findPage(new Page<HostInventory>(request, response), hostInventory); 
		model.addAttribute("page", page);
		return "modules/inventory/hostInventoryList";
	}

	/**
	 * 主机总体监控（大屏幕监控页）
	 * @param hostInventory
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "listLoc")
	public String listLoc(HostInventory hostInventory, HttpServletRequest request, HttpServletResponse response, Model model) {
		List<Map> hostLocList = hostInventoryService.findDetailedPage(hostInventory);
		model.addAttribute("list", hostLocList);
		String type = request.getParameter("type");
		String big = request.getParameter("big");
		
		//获取当前值班人员的信息
		ZlmtDutySheet zlmtDutySheet = new ZlmtDutySheet();
		zlmtDutySheet.setThruTime(new Date());
		zlmtDutySheet.setDutyStatus("0");
		List<ZlmtDutySheet> result = zlmtDutySheetService.findList(zlmtDutySheet);
		String userName = "";
		String mobilePhoneNum = "";
		if(result != null && result.size() > 0){
			ZlmtDutySheet zlSheet = result.get(0);
			userName = zlSheet.getSysUserName();
			mobilePhoneNum = zlSheet.getMobilePhoneNum();
		}
		
		if(null != type && type.equals("real")){ // 真实监控页面
			model.addAttribute("message", "欢迎进入机房监控");
			int rownum = (hostLocList==null||hostLocList.size()==0) ? 0 : hostLocList.size();
			model.addAttribute("rowNum", rownum);
			model.addAttribute("big", big);
			model.addAttribute("userName", userName);
			model.addAttribute("mobilePhoneNum", mobilePhoneNum);
			return "modules/inventory/monitorpage";
		}else{  //跳转到demo 页面，预览全局效果
			model.addAttribute("message", "欢迎进入机房监控(DEMO)");
			return "modules/inventory/monitorpagedemo";
		}
	}

	@RequestMapping(value = "form")
	public String form(HostInventory hostInventory, Model model) {
		model.addAttribute("hostInventory", hostInventory);
		return "modules/inventory/hostInventoryForm";
	}

	@RequestMapping(value = "save")
	public String save(HostInventory hostInventory, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, hostInventory)){
			return form(hostInventory, model);
		}
		hostInventoryService.save(hostInventory);
		addMessage(redirectAttributes, "保存资产信息成功");
		return "redirect:"+Global.getAdminPath()+"/inventory/hostInventory/detailedForm?id="+hostInventory.getId();
	}


	@RequestMapping(value = "detailedForm")
	public String detailedForm(HostInventory hostInventory, Model model) {
		if(StringUtils.isNotEmpty(hostInventory.getId())){
			List<ZlmtCabinet> availableCabinets = zlmtCabinetService.findList(new ZlmtCabinet());
			model.addAttribute("availableCabinets", availableCabinets);
			ZlmtHostsCabinet zlmtHostsCabinet = new ZlmtHostsCabinet();
			zlmtHostsCabinet.setHostid(hostInventory.getId());
			List<ZlmtHostsCabinet> possibles = zlmtHostsCabinetService.findList(zlmtHostsCabinet);
			if(!Collections3.isEmpty(possibles)){
				ZlmtHostsCabinet choosedValue = possibles.get(0);
				ZlmtCabinet choosedCabinet = null;
				if(!Collections3.isEmpty(availableCabinets)){
					for(ZlmtCabinet cabinet:availableCabinets){
						if(cabinet.getId().equals(choosedValue.getCabinetId())){
							choosedCabinet = cabinet;
							break;
						}
					}
				}
				model.addAttribute("choosedLoc", choosedValue);
				model.addAttribute("choosedCabinet", choosedCabinet);
			}

			ZlmtHostsAccessory zlmtHostsAccessory = new ZlmtHostsAccessory();
			zlmtHostsAccessory.setHostid(hostInventory.getId());
			List<ZlmtHostsAccessory> accessoryList = zlmtHostsAccessoryService.findList(zlmtHostsAccessory);
			model.addAttribute("zlmtHostsAccessory",zlmtHostsAccessory);
			if(!Collections3.isEmpty(accessoryList)){
				model.addAttribute("accessoryList",accessoryList);
			}
			HostLinks hostLinks = new HostLinks();
			hostLinks.setFromHostid(hostInventory.getId());
			hostLinks.setFromHostalias(hostInventory.getAlias());
			hostLinks.setFromHostname(hostInventory.getName());
			hostLinks.setFromHostType(hostInventory.getType());
			List<HostLinks> linkList = hostLinksService.findList(hostLinks);
			model.addAttribute("hostLinks", hostLinks);
			if(!Collections3.isEmpty(linkList)){
				model.addAttribute("linkList", linkList);
			}

			ZlmtResourceUser zlmtResourceUser = new ZlmtResourceUser();
			zlmtResourceUser.setHostid(hostInventory.getId());
			List<ZlmtResourceUser> zlmtResourceUserList = zlmtResourceUserService.findList(zlmtResourceUser);
			model.addAttribute("zlmtResourceUser",zlmtResourceUser);
			if(!Collections3.isEmpty(zlmtResourceUserList)){
				model.addAttribute("userList", zlmtResourceUserList);
			}

			ZlmtMaintenanceRecord maintenanceRecord = new ZlmtMaintenanceRecord();
			maintenanceRecord.setHostid(hostInventory.getId());
			List<ZlmtMaintenanceRecord> maintenanceRecordList = zlmtMaintenanceRecordService.findList(maintenanceRecord);
			model.addAttribute("zlmtMaintenanceRecord",maintenanceRecord);
			if(!Collections3.isEmpty(maintenanceRecordList)){
				model.addAttribute("maintenanceRecordList", maintenanceRecordList);
			}
		}
		model.addAttribute("hostInventory", hostInventory);
		return "modules/inventory/hostInventoryDetailedForm";
	}

	@RequestMapping(value = "detailedSave")
	public String detailedSave(HostInventory hostInventory, Model model, RedirectAttributes redirectAttributes) {
		if(StringUtils.isNotEmpty(hostInventory.getCabinetId())){
			if(StringUtils.isNotEmpty(hostInventory.getHostLocCode()) && StringUtils.isNotEmpty(hostInventory.getUnitUsed()) && StringUtils.isNotEmpty(hostInventory.getUnitUsedCode())){
				if(hostInventory.getUnitUsed().equals("1") || hostInventory.getUnitUsed().equals("2") || hostInventory.getUnitUsed().equals("6")){
					ZlmtHostsCabinet zlmtHostsCabinet = new ZlmtHostsCabinet();
					zlmtHostsCabinet.setCabinetId(hostInventory.getCabinetId());
					List<ZlmtHostsCabinet> possibles = zlmtHostsCabinetService.findList(zlmtHostsCabinet);
					if(!Collections3.isEmpty(possibles)){
						for(ZlmtHostsCabinet hostsCabinet:possibles){
							if(hostsCabinet.getHostid().equals(hostInventory.getId())){
								continue;
							}else {
								if(hostsCabinet.getHostLocCode().equals(hostInventory.getHostLocCode())){
									model.addAttribute("message","上架位置信息录入不规范，主机在机柜的序号已经被占用");
									return form(hostInventory, model);
								}
								boolean conflict = checkLoc(hostInventory, hostsCabinet);
								if(conflict){
									model.addAttribute("message","上架未知已经被占用，请重新录入");
									return form(hostInventory, model);
								}
							}
						}
					}
				}else {
					model.addAttribute("message","上架位置信息录入不规范");
					return form(hostInventory, model);
				}
			} else {
				model.addAttribute("上架位置信息不全，不能上架");
				return form(hostInventory, model);
			}
			HostInventory oldhostInventory = hostInventoryService.get(hostInventory.getId());
			oldhostInventory.setCabinetId(hostInventory.getCabinetId());
			oldhostInventory.setUnitUsedCode(hostInventory.getUnitUsedCode());
			oldhostInventory.setUnitUsed(hostInventory.getUnitUsed());
			oldhostInventory.setHostLocCode(hostInventory.getHostLocCode());
			hostInventoryService.save(oldhostInventory);
			model.addAttribute("id", oldhostInventory.getId());
		}

		addMessage(redirectAttributes, "保存上架信息成功");

		return "redirect:"+Global.getAdminPath()+"/inventory/hostInventory/detailedForm?id="+hostInventory.getId();
	}


	@RequestMapping(value = "addAccessory")
	public String addAccessory(ZlmtHostsAccessory zlmtHostsAccessory, Model model, RedirectAttributes redirectAttributes) {
		if(StringUtils.isNotEmpty(zlmtHostsAccessory.getHostid())){
			zlmtHostsAccessoryService.save(zlmtHostsAccessory);
		}else {
			addMessage(redirectAttributes, "添加配件失败");
			return "redirect:"+Global.getAdminPath()+"/inventory/hostInventory?repage";
		}
		addMessage(redirectAttributes, "保存配件信息成功");
		return "redirect:"+Global.getAdminPath()+"/inventory/hostInventory/detailedForm?id="+zlmtHostsAccessory.getHostid();
	}

	@RequestMapping(value = "deleteAccessory")
	public String deleteAccessory(String hostid, String id, RedirectAttributes redirectAttributes){
		if(StringUtils.isNotEmpty(hostid) && StringUtils.isNotEmpty(id)){
			ZlmtHostsAccessory accessory = new ZlmtHostsAccessory();
			accessory.setId(id);
			zlmtHostsAccessoryService.delete(accessory);
		}else {
			addMessage(redirectAttributes, "参数缺失，删除失败");
		}
		return "redirect:"+Global.getAdminPath()+"/inventory/hostInventory/detailedForm?id="+hostid;
	}

	@RequestMapping(value = "addLink")
	public String addLink(HostLinks hostLinks, Model model, RedirectAttributes redirectAttributes){
		if(StringUtils.isNotEmpty(hostLinks.getFromHostid()) && StringUtils.isNotEmpty(hostLinks.getToHostid())){
			HostInventory toHost = hostInventoryService.get(hostLinks.getToHostid());
			hostLinks.setToHostalias(toHost.getAlias());
			hostLinks.setToHostname(toHost.getName());
			hostLinks.setToHostType(toHost.getType());
			hostLinks.setFromTime(new Date());
			hostLinks.setThruTime(DateUtils.addYears(new Date(), 100));
			hostLinksService.save(hostLinks);
		}else {
			addMessage(redirectAttributes, "添加topo连接失败");
			return "redirect:"+Global.getAdminPath()+"/inventory/hostInventory?repage";
		}
		addMessage(redirectAttributes, "添加topo连接信息成功");
		return "redirect:"+Global.getAdminPath()+"/inventory/hostInventory/detailedForm?id="+hostLinks.getFromHostid();
	}

	@RequestMapping(value = "deleteLink")
	public String deleteLink(String hostId, String id, RedirectAttributes redirectAttributes ){
		if(StringUtils.isNotEmpty(hostId) && StringUtils.isNotEmpty(id)){
			HostLinks hostLinks = hostLinksService.get(id);
			if(hostId.equals(hostLinks.getFromHostid()) || hostId.equals(hostLinks.getToHostid())){
				hostLinks.setThruTime(new Date());
				hostLinksService.save(hostLinks);
			}else {
				addMessage(redirectAttributes, "删除关联主机失败");
				return "redirect:"+Global.getAdminPath()+"/inventory/hostInventory?repage";
			}
			addMessage(redirectAttributes, "删除关联主机成功");
			return "redirect:"+Global.getAdminPath()+"/inventory/hostInventory/detailedForm?id="+hostId;
		}else {
			addMessage(redirectAttributes, "参数有误");
			return "redirect:"+Global.getAdminPath()+"/inventory/hostInventory?repage";
		}
	}

	@RequestMapping(value = "addResourceUser")
	public String addResourceUser(ZlmtResourceUser zlmtResourceUser, Model model, RedirectAttributes redirectAttributes) {
		if(StringUtils.isNotEmpty(zlmtResourceUser.getHostid()) && StringUtils.isNotEmpty(zlmtResourceUser.getUser().getId())){
			zlmtResourceUserService.save(zlmtResourceUser);
		}else {
			addMessage(redirectAttributes, "添加干系人失败");
			return "redirect:"+Global.getAdminPath()+"/inventory/hostInventory?repage";
		}
		addMessage(redirectAttributes, "保存干系人成功");
		return "redirect:"+Global.getAdminPath()+"/inventory/hostInventory/detailedForm?id="+zlmtResourceUser.getHostid();
	}

	@RequestMapping(value = "deleteResourceUser")
	public String  deleteResourceUser(String hostid, String id, RedirectAttributes redirectAttributes){
		if(StringUtils.isNotEmpty(hostid) && StringUtils.isNotEmpty(id)){
			ZlmtResourceUser resourceUser = zlmtResourceUserService.get(id);
			if(hostid.equals(resourceUser.getHostid())){
				resourceUser.setThruTime(new Date());
				zlmtResourceUserService.save(resourceUser);
			}else {
				addMessage(redirectAttributes, "删除干系人失败");
				return "redirect:"+Global.getAdminPath()+"/inventory/hostInventory?repage";
			}
			addMessage(redirectAttributes, "删除干系人成功");
			return "redirect:"+Global.getAdminPath()+"/inventory/hostInventory/detailedForm?id="+hostid;
		}else {
            addMessage(redirectAttributes, "参数有误");
            return "redirect:"+Global.getAdminPath()+"/inventory/hostInventory?repage";
        }
	}

	@RequestMapping(value = "delete")
	public String delete(HostInventory hostInventory, RedirectAttributes redirectAttributes) {
		hostInventoryService.delete(hostInventory);
		addMessage(redirectAttributes, "删除资产信息成功");
		return "redirect:"+Global.getAdminPath()+"/inventory/hostInventory/?repage";
	}

	private boolean checkLoc(HostInventory hostInventory, ZlmtHostsCabinet hostsCabinet) {
		try {
			int thisHostMin = Integer.parseInt(hostInventory.getUnitUsedCode()) - Integer.parseInt(hostInventory.getUnitUsed()) + 1;
			int thisHostMax = Integer.parseInt(hostInventory.getUnitUsedCode());
			int otherHostMin = Integer.parseInt(hostsCabinet.getUnitUsedCode()) - Integer.parseInt(hostsCabinet.getUnitUsed()) + 1;
			int otherHostMax = Integer.parseInt(hostsCabinet.getUnitUsedCode());
			if(thisHostMin > thisHostMax  || otherHostMin > otherHostMax){
				return true;
			}
			if(thisHostMin <= otherHostMin && otherHostMin <= thisHostMax){
				return true;
			}
			if(thisHostMin <= otherHostMax && otherHostMax <= thisHostMax){
				return true;
			}
		}catch (Exception e){
			return true;
		}
		return false;
	}

}
